package qualomelhor.server;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//import org.openid4java.association.AssociationException;
//import org.openid4java.consumer.ConsumerManager;
//import org.openid4java.consumer.VerificationResult;
//import org.openid4java.discovery.DiscoveryException;
//import org.openid4java.discovery.DiscoveryInformation;
//import org.openid4java.discovery.Identifier;
//import org.openid4java.message.AuthSuccess;
//import org.openid4java.message.MessageException;
//import org.openid4java.message.ParameterList;
//import org.openid4java.message.ax.AxMessage;
//import org.openid4java.message.ax.FetchResponse;
import qualomelhor.database.Usuario;
import qualomelhor.database.ParametrosSistema.OrigemLogin;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class CallbackOpenIdServlet extends HttpServlet {
    private static final long serialVersionUID = 1657390011452788111L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	/*
    	System.out.println("callback openId chamado!!!!!");

    	ParameterList resp =
                new ParameterList(request.getParameterMap());

        // retrieve the previously stored discovery information
        DiscoveryInformation discovered = (DiscoveryInformation)
                request.getSession().getAttribute("openid-disc");

        // extract the receiving URL from the HTTP request
        StringBuffer receivingURL = request.getRequestURL();
        String queryString = request.getQueryString();
        if (queryString != null && queryString.length() > 0)
            receivingURL.append("?").append(request.getQueryString());

        ConsumerManager manager = (ConsumerManager)request.getSession().getAttribute("MANAGER");

        // verify the response; ConsumerManager needs to be the same
        // (static) instance used to place the authentication request
        VerificationResult verification = null;
		try {
			verification = manager.verify(receivingURL.toString(), resp, discovered);

	        // examine the verification result and extract the verified identifier
	        Identifier verified = verification.getVerifiedId();
	        if (verified != null)
	        {
	            AuthSuccess authSuccess =
	                    (AuthSuccess) verification.getAuthResponse();

	            if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
	                FetchResponse fetchResp = (FetchResponse) authSuccess
	                        .getExtension(AxMessage.OPENID_NS_AX);

	                List emails = fetchResp.getAttributeValues("email");
	                String email = (String) emails.get(0);
	            }

	            //return verified;  // success

	            DAO d = new DAO();
				Usuario u = d.getUsuarioTwitter(String.valueOf(verified.getIdentifier()));
				if (u == null) {
					System.out.println("novo usuario do twitter sendo criado..");
					u = new Usuario("", String.valueOf(verified.getIdentifier()), OrigemLogin.TWITTER.getSiteOrigem(), verified.getIdentifier(), "", "", "", "", "", "", true, new Date());
				} else {
					System.out.println("atualizando usuario do openId..");
					u.setAccessToken(verified.getIdentifier());
				}
				d.gravaNovoUsuario(u);

				HttpSession session = request.getSession(true);

				@SuppressWarnings("unchecked")
				HashMap<String, Object> mapSession = (HashMap<String, Object>)session.getAttribute("SESSIONVAR"); 

				mapSession.put("USUARIOATUAL", u);
				session.setAttribute("SESSIONVAR", mapSession);
				session.setAttribute("USUARIOATUAL", u);
				System.out.println("SETOU O USUARIO ATUAL: " + u.getNomeUsuario() + ", Admin:" + u.getAdmin());

				response.sendRedirect("/logado.jsp?nome=" + u.getNomeUsuario() + "&id=" + verified.getIdentifier());
	        }

		} catch (MessageException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DiscoveryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AssociationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        System.out.println("Fim!!");
        //response.sendRedirect(request.getContextPath() + "/");
         * 
         */
    }
}